package com.example.layered_arch.example.service;

import com.example.layered_arch.example.dto.UserRegistrationRequest;
import com.example.layered_arch.example.repository.UserRepository;
import com.example.layered_arch.example.entity.User;
import com.example.layered_arch.example.entity.User.AccountRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class UserRegistrationService {

    @Autowired
    private UserRepository userRepository;

    // 用户注册方法
    public Map<String, String> register(UserRegistrationRequest registrationRequest) {
        Map<String, String> response = new HashMap<>();

        // 校验用户名是否已存在
        if (userRepository.existsByUsername(registrationRequest.getUsername())) {
            response.put("status", "error");
            response.put("message", "Username already exists!");
            return response;
        }

        // 校验手机号是否已存在
        if (userRepository.existsByPhoneNumber(registrationRequest.getPhone())) {
            response.put("status", "error");
            response.put("message", "Phone number already exists!");
            return response;
        }

        // 校验邮箱是否已存在
        if (userRepository.existsByEmail(registrationRequest.getEmail())) {
            response.put("status", "error");
            response.put("message", "Email already exists!");
            return response;
        }

        // 校验邮箱格式
        if (!isValidEmail(registrationRequest.getEmail())) {
            response.put("status", "error");
            response.put("message", "Invalid email format!");
            return response;
        }

        // 校验手机号码格式
        if (!isValidPhoneNumber(registrationRequest.getPhone())) {
            response.put("status", "error");
            response.put("message", "Invalid phone number format!");
            return response;
        }

        // 校验密码强度
        if (!isValidPassword(registrationRequest.getPassword())) {
            response.put("status", "error");
            response.put("message", "Password does not meet the required strength (min 8 chars, including letters and numbers)!");
            return response;
        }

        // 将字符串日期转换为 Date 类型
        Date birthDate = null;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            birthDate = dateFormat.parse(registrationRequest.getBirthDate());
        } catch (ParseException e) {
            response.put("status", "error");
            response.put("message", "Invalid birth date format! Expected format: yyyy-MM-dd");
            return response;
        }

        // 将 role 从 String 转换为 AccountRole 枚举类型
        AccountRole role;
        try {
            role = AccountRole.valueOf(registrationRequest.getRole().toUpperCase());
        } catch (IllegalArgumentException e) {
            response.put("status", "error");
            response.put("message", "Invalid role! Accepted values are: user, seller, admin.");
            return response;
        }

        // 保存用户信息到数据库
        User newUser = new User(
                registrationRequest.getUsername(),
                registrationRequest.getPassword(),
                registrationRequest.getPhone(),
                registrationRequest.getEmail(),
                registrationRequest.getFullName(),
                registrationRequest.getGender(),
                birthDate,
                registrationRequest.getAddress(),
                registrationRequest.getAvatarUrl(), // 保存头像路径
                role
        );

        // 保存到数据库
        userRepository.save(newUser);

        response.put("status", "success");
        response.put("message", "User registered successfully!");
        return response;
    }

    // 校验邮箱格式
    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
        Pattern pattern = Pattern.compile(emailRegex);
        return pattern.matcher(email).matches();
    }

    // 校验手机号格式
    private boolean isValidPhoneNumber(String phone) {
        String phoneRegex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(phoneRegex);
        return pattern.matcher(phone).matches();
    }

    // 校验密码强度
    private boolean isValidPassword(String password) {
        return password.length() >= 8 && password.matches(".*[A-Za-z].*") && password.matches(".*\\d.*");
    }
}
